'use strict';
const Controller = require('egg').Controller;
const MAX = 1000;
const NODE = 17;

class ToGoController extends Controller {
  async index() {
    const ctx = this.ctx;
    let a = ctx.query.key1;
    let b = ctx.query.key2;
    a = await ctx.service.nameses.findName(a);
    const key1 = a.data[0]['nameOther'];
    b = await ctx.service.nameses.findName(b);
    const key2 = b.data[0]['nameOther'];
    let data = await ctx.service.link.find(key1,key2);
    if(data.data == 0){
       this.dijkstra(key1);
       data = await ctx.service.link.find(key1,key2);
    }
    ctx.body = data;
    return data;
  }



/*
  实现最短路径算法和查找 
*/
  async dijkstra(key){
    const ctx = this.ctx;
    let a = await ctx.service.linkClass.find();
    const map = a.data;                     //链接矩阵
    let dis = new Int32Array(NODE);          // 记录src到其它各个顶点的最短路径长度
    let mark = new Int32Array(NODE);         // 标记数组，判断哪些src到哪些顶点的最短路径已经求出
    let i,j,min,k,tmp,src;

    a = await ctx.service.nameses.findAll();
    const dictionaries = a.data;
    for (let index = 0; index < dictionaries.length; index++) {
      if (key === dictionaries[index]['nameOther']) {
        src = dictionaries[index]['id'];
        break;
      }     
    }

    for (i = 0; i < 17; i++) {
      dis[i] = map[src][i.toString()];
      mark[i] = 0;
    }
    /*
      n-1次主循环，每次循环求得src到某个顶点v的最短路径
    */ 
    for (i = 1; i < 17; i ++) {
      min = MAX;
      k = src;
      for (j = 0; j < 17; j ++) {
        if (!mark[j] && dis[j] < min) {
          k = j;
          min = dis[j];
        }
      }
      mark[k] = 1;
   
      /*
       更新src到其它各顶点的最短路径
       */
      for (j = 0; j < 23; j ++) {
        tmp = map[k][j.toString()] + dis[k];
        if (tmp < dis[j] && mark[j] == 0) {
          dis[j] = tmp;
        }
      }
    }
    this.saveData(key,dis,mark);
  }
  /*
    name<==>id方法
  */

  async transform(key){
    const ctx = this.ctx;
    let a = await ctx.service.nameses.findAll();
    const dictionaries = a.data;
    for (let index = 0; index < dictionaries.length; index++) {
      if (key === dictionaries[index]['nameOther']) {
        let result = dictionaries[index]['id'];
        return result;
      }     
    }

  }
  /*
    将dijkstra数据入库
  */

  async saveData(key,dis,mark){
    const ctx = this.ctx;
    for (let index = 0; index < dis.length; index++) {
      let k = await ctx.service.nameses.find(index);
      k = k.data[0]['nameOther'];
      if (mark[index]!=0) {
        await ctx.service.link.saveData(key,k,dis[index]);
      }
      
    }
  }
}

module.exports = ToGoController;
